// ResizeWrapper.tsx
import * as echarts from 'echarts';
import React, { ReactNode, useEffect, useRef } from 'react';
import { useResizeDetector } from 'react-resize-detector';

interface ResizeWrapperProps {
  children: ReactNode;
}

const ResizeWrapper: React.FC<ResizeWrapperProps> = ({ children }) => {
  const wrapperRef = useRef<HTMLDivElement | null>(null);

  const onResize = () => {
    if (wrapperRef.current) {
      const chartElements = wrapperRef.current.querySelectorAll('.echarts-for-react');
      chartElements.forEach((chartElement) => {
        const chartInstance = echarts.getInstanceByDom(chartElement as HTMLDivElement);
        if (chartInstance) {
          chartInstance.resize();
        }
      });
    }
  };

  const { ref: resizeRef } = useResizeDetector({
    onResize,
  });

  useEffect(() => {
    if (resizeRef) {
      resizeRef(wrapperRef.current);
    }
  }, [resizeRef]);

  return <div ref={wrapperRef}>{children}</div>;
};

export default ResizeWrapper;
